package freemarker.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.etlmaster.executor.EtlMasterException;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class FreeMarkerTemplate {
	private static Logger log = LoggerFactory
			.getLogger(FreeMarkerTemplate.class);
	private Configuration freemarker_cfg = null;

	protected Configuration getFreeMarkerCFG() throws TemplateException {
		if (null == freemarker_cfg) {
			freemarker_cfg = new Configuration();
			freemarker_cfg.setClassForTemplateLoading(this.getClass(), "");
		}
		return freemarker_cfg;
	}

	public static String getFpl(String fplName, Map<String, String> data) {
		InputStream in = null;
		StringWriter sw = null;
		try {

			in = FreeMarkerTemplate.class.getClassLoader().getResourceAsStream(
					"conf/freemarker/" + fplName + ".fpl");
			String text = IOUtils.toString(new InputStreamReader(in, "utf-8"));
			Template template = new Template(null, text, null);

			sw = new StringWriter();
			template.process(data, sw);
			in.close();
			sw.close();
			return sw.toString();

		} catch (Exception e) {
			
			try {
				if (in != null)
					in.close();
				if (sw != null)
					sw.close();
			} catch (IOException e1) {
				
			}

			log.error(e.getMessage());
			throw new EtlMasterException(e.getMessage());

		}

	}
	public static String getFpls(String fplName, Map<String, Object> data) {

		InputStream in = null;
		StringWriter sw = null;
		try {
			in = FreeMarkerTemplate.class.getClassLoader().getResourceAsStream(
					"conf/freemarker/" + fplName + ".fpl");
			String text = IOUtils.toString(new InputStreamReader(in, "utf-8"));
			Template template = new Template(null, text, null);

			sw = new StringWriter();
			template.process(data, sw);
			in.close();
			sw.close();
			return sw.toString();

		} catch (Exception e) {
			try {
				if (in != null)
					in.close();
				if (sw != null)
					sw.close();
			} catch (IOException e1) {
			
			}

			log.error(e.getMessage());
			e.printStackTrace();
			return null;

		}

	}

}
